//
//  EmployeeManagerViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/4/12.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
import CRRefresh
import SwiftyJSON
import HandyJSON

class EmployeeManagerViewController: BaseViewController {

    @IBOutlet var employeeCollectionview: UICollectionView!
    
    let employeeCell = "employeeCell"
    var employees: [EmployeeModel]?
    var page: Int?
    var doType: Int? //1 默认  2 删除  3 编辑
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configView()
        page = 1
        doType = 1
        requstEmpolyList(page: page!, pageSize: pageSize)
        requestEmployeeTypeList()
        requestStoreList()
    }
    func configView() -> Void {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 1
        employeeCollectionview.frame = .zero
        employeeCollectionview.collectionViewLayout = layout
        employeeCollectionview.delegate = self
        employeeCollectionview.dataSource = self
       employeeCollectionview.register(UINib(nibName: "EmployeeCollectionViewCell", bundle: nil),forCellWithReuseIdentifier: employeeCell)
        employeeCollectionview.showsVerticalScrollIndicator = false
        employeeCollectionview.alwaysBounceVertical = true;
        employeeCollectionview.backgroundColor = BaseColor.BackGroundColor
        employeeCollectionview.cr.addHeadRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol) { [weak self] in
            self?.page = 1
            self?.requstEmpolyList(page: (self?.page)!, pageSize: pageSize)
        }
        employeeCollectionview.cr.addFootRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol)  { [weak self] in
           self?.page! += 1
           self?.requstEmpolyList(page: (self?.page)!, pageSize: pageSize)
        }

    }
    
    //按钮事件
    
    
    @IBAction func appBtnPress(_ sender: UIButton) {
        
        doType = 1
        employeeCollectionview.reloadData()
        
        let addEmployeeView = addEmpolyeePopView.getAddempolyeePopView()
        addEmployeeView.callBackBlock { (boolValue) in
            switch boolValue {
            case true:
                self.requestAddEmployee(name: addEmployeeView.nameTF.text!, phone:addEmployeeView.phoneTF.text!, age: addEmployeeView.ageTF.text!, employeeType: (addEmployeeView.workTypeBtn.titleLabel?.text)!, employeeRole: addEmployeeView.role_id, store:addEmployeeView.store_id, sex: addEmployeeView.sex_id, workTime:addEmployeeView.workTimeTF.text!, goodatArea:addEmployeeView.goodAtAreaTF.text!)
                 bgWindow?.hidBackgroundWindow()
            case false:
                 bgWindow?.hidBackgroundWindow()
            }
        }
        bgWindow = DSHCBcakgroundWindow.setupBackgroundWindowAndShow()
        bgWindow?.shake(toShow: addEmployeeView)
    }
    
    @IBAction func deleteBtnPress(_ sender: UIButton) {
        doType = 2
        employeeCollectionview.reloadData()
    }
    
    @IBAction func editBtnPress(_ sender: UIButton) {
        doType = 3
        employeeCollectionview.reloadData()

    }
    
    
    
    //网络请求
    func requstEmpolyList(page:Int,pageSize:String) -> Void {
        
//        NetworkRequest.sharedInstance.postRequest(urlString: employeeListUrl, params: ["page": page,"pageSize":pageSize,"sid":UserModel.shareUser.data?.storeId ?? String()], success: { (response) in
//
////            if self.pageNum == 0 {
//
////                self.employee?.data?.removeAll()
////                if let orderData = data {
////                    self.employee?.data? = EmployeeModel.deserialize(from: orderData.rawString()) as? [Order]
////                }
//
////            self.employee = EmployeeModel.deserialize(from: response)
////            self.employee = response.
//
//            var basemodel = BaseResponse<EmployeeModel>?.self
//
//            basemodel = BaseResponse.deserialize(from: response)
//
//            print("成功")
//        }) { (error) in
//            print("失败")
//        }
        
        Alamofire.request(employeeListUrl, method:.post, parameters: ["page": page,"pageSize":pageSize,"sid":UserModel.shareUser.data?.storeId ?? String()])
            .responseString { response in
                self.employeeCollectionview?.cr.endHeaderRefresh();                self.employeeCollectionview?.cr.endLoadingMore()
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<EmployeeModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    switch basemodel.status! {
                        case true:
                            if page == 1 {
                                self.employees?.removeAll()
                                self.employees = basemodel.data?.data
                            }else {
                                if ((basemodel.data?.data?.count)! > 0) {
                                    self.employees! += (basemodel.data?.data)!
                                }else {
                                    return
                                }
                            }
                        print("数据请求成功")
                     self.employeeCollectionview.reloadData()

                        case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    
                    }

                case false:
                    print(response.result.error!)
                }
        }
    }
    //添加员工
    func requestAddEmployee(name:String,phone:String,age:String,employeeType:String,employeeRole:String,store:String,sex:String,workTime:String,goodatArea:String) -> Void {
        
        let param =
               ["name":name,
                "account":phone,
                "age":age,
                "sex":sex,
                "work_id":employeeType,
                "status":"1",
                "role_id":employeeRole,
                "sid":store,
                "work_time":workTime,
                "skill":goodatArea,
                ]
        
        Alamofire.request(addemployeeUrl, method:.post, parameters:param)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<EmployeeModel>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!

                    switch basemodel.status! {
                    case true:
                        print("新增成功")
                        self.page = 1
                        self.requstEmpolyList(page: self.page!, pageSize: pageSize)
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
            
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    //获取员工职位
    func requestEmployeeTypeList() -> Void {
        
        
        Alamofire.request(employeeTypeList, method:.post, parameters:nil)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<EmployeeTypeModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    switch basemodel.status! {
                    case true:
                        UserModel.shareUser.data?.employeeTypes = basemodel.data?.data
                        print("数据请求成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    //获取店铺列表
    func requestStoreList() -> Void {
        
        
        Alamofire.request(storeList, method:.post, parameters:["uid":UserModel.shareUser.data?.uid ?? String()])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<EmployeeStoreModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:

                        UserModel.shareUser.data?.employeeStores = basemodel.data?.data
                        print("数据请求成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    //停用员工
    func requestNotUseEmployee(userId:String) -> Void {
        
        
        Alamofire.request(deleteemployeeUrl, method:.post, parameters:["uid":userId])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        self.page = 1
                        self.requstEmpolyList(page: self.page!, pageSize: pageSize)
                        print("停用成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    //启用
    func requestUseEmployee(userId:String) -> Void {
        
        
        Alamofire.request(activeemployeeUrl, method:.post, parameters:["uid":userId])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        self.page = 1
                        self.requstEmpolyList(page: self.page!, pageSize: pageSize)
                        print("启用成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    
    //获取员工详情
    func requestEmployeeDetails(userId:String) -> Void {
        
        
        Alamofire.request(employeeDetailsUrl, method:.post, parameters:["uid":userId])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<EmployeeModel>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        self.popEditEmployeeEvent(model: basemodel.data!)
                        print("获取成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    //编辑指定员工
    func requestEditEmployee(userId:String,name:String,phone:String,age:String,employeeType:String,employeeRole:String,store:String,sex:String,workTime:String,goodatArea:String) -> Void {
        
        
        let param =
            ["name":name,
             "account":phone,
             "age":age,
             "sex":sex,
             "work_id":employeeType,
             "status":"1",
             "role_id":employeeRole,
             "sid":store,
             "uid":userId,
             "work_time":workTime,
             "skill":goodatArea
             ]
        
        Alamofire.request(editemployeeUrl, method:.post, parameters:param)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        print("编辑成功")
                        self.page = 1
                        self.requstEmpolyList(page: self.page!, pageSize: pageSize)
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
//弹出编辑员工弹框
    func popEditEmployeeEvent(model:EmployeeModel) -> Void {
        let addEmployeeView = addEmpolyeePopView.getAddempolyeePopView()
        addEmployeeView.titleLabel.text = "编辑员工"
        addEmployeeView.nameTF.text = model.name
        addEmployeeView.phoneTF.text = model.account
        addEmployeeView.ageTF.text = model.age
        addEmployeeView.work_id = model.work_id
        addEmployeeView.role_id = model.role_id
        addEmployeeView.store_id = model.store_id
        addEmployeeView.sex_id = model.sex
        addEmployeeView.workTimeTF.text = model.sex
        addEmployeeView.goodAtAreaTF.text = model.sex
        addEmployeeView.phoneTF.isEnabled = false
        addEmployeeView.workTypeBtn.setTitle(model.work_name, for: .normal)
        addEmployeeView.storeBtn.setTitle(model.store_name, for: .normal)
        if (model.sex == "1"){
            addEmployeeView.sexBtn.setTitle("男", for: .normal)
        }else {
            addEmployeeView.sexBtn.setTitle("女", for: .normal)
        }
        switch model.role_id{
        case "1":
            addEmployeeView.workRoleBtn.setTitle("老板", for: .normal)
        case "2":
            addEmployeeView.workRoleBtn.setTitle("店长", for: .normal)
        default:                            addEmployeeView.workRoleBtn.setTitle("店员", for: .normal)
        }
        
        
        
        
        addEmployeeView.callBackBlock { (boolValue) in
            switch boolValue {
            case true:
                self.requestEditEmployee(userId:model.uid, name:addEmployeeView.nameTF.text!, phone:addEmployeeView.phoneTF.text!, age:addEmployeeView.ageTF.text!, employeeType:addEmployeeView.work_id,employeeRole:addEmployeeView.role_id,store:addEmployeeView.store_id, sex: addEmployeeView.sex_id,workTime:addEmployeeView.workTimeTF.text!, goodatArea:addEmployeeView.goodAtAreaTF.text!)
                bgWindow?.hidBackgroundWindow()
            case false:
                bgWindow?.hidBackgroundWindow()
            }
        }
        bgWindow = DSHCBcakgroundWindow.setupBackgroundWindowAndShow()
        bgWindow?.shake(toShow: addEmployeeView)
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension EmployeeManagerViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.employees?.count ?? 0
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: employeeCell, for: indexPath) as!EmployeeCollectionViewCell
        cell.roundCorner(radius: 5)
        let model = employees![indexPath.item]
        cell.nameLabel.text = model.name
        cell.phoneLabel.text = model.account
        cell.workTypeLabel.text = model.work_name
        cell.sendStatusBlock {
            switch self.doType {
            case 1://默认
            print("默认")
            case 2://启用或者停用
                if model.status == "1" {//停用
                    let alertController = UIAlertController(title: "操作员工",
                                                            message: "您确定要停用该员工吗？", preferredStyle: .alert)
                    let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                    let okAction = UIAlertAction(title: "停用", style: .default, handler: {
                        action in
                        print("停用")
                        self.requestNotUseEmployee(userId: model.uid)
                    })
                    alertController.addAction(cancelAction)
                    alertController.addAction(okAction)
                    self.present(alertController, animated: true, completion: nil)
                }else {//启用
                    let alertController = UIAlertController(title: "操作员工",
                                                            message: "您确定要启用该员工吗？", preferredStyle: .alert)
                    let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                    let okAction = UIAlertAction(title: "启用", style: .default, handler: {
                        action in
                        print("启用")
                        self.requestUseEmployee(userId: model.uid)
                    })
                    alertController.addAction(cancelAction)
                    alertController.addAction(okAction)
                    self.present(alertController, animated: true, completion: nil)
                }
            default://修改
            self.requestEmployeeDetails(userId: model.uid)
            }
        }
        if model.status == "1" {
            switch doType {
            case 1:
                cell.empolyerStatusLabel.setTitle("已启用", for: .normal)
                cell.empolyerStatusLabel.setTitleColor(BaseColor.NavColor, for: .normal)
                cell.empolyerStatusLabel.setImage(UIImage.init(named: "")?.withRenderingMode(.alwaysOriginal), for: .normal)
            case 2:
                cell.empolyerStatusLabel.setTitle("", for: .normal);
           cell.empolyerStatusLabel.setImage(UIImage.init(named: "启用icon")?.withRenderingMode(.alwaysOriginal), for: .normal)
                

            default:
                cell.empolyerStatusLabel.setTitle("", for: .normal); cell.empolyerStatusLabel.setImage(UIImage.init(named: "edit")?.withRenderingMode(.alwaysOriginal), for: .normal)
            }
            
        }else {
            switch doType {
            case 1:
                cell.empolyerStatusLabel.setTitle("已停用", for: .normal)
                cell.empolyerStatusLabel.setTitleColor(UIColor.red, for: .normal)
                cell.empolyerStatusLabel.setImage(UIImage.init(named: ""), for: .normal)
            case 2:
                cell.empolyerStatusLabel.setTitle("", for: .normal); cell.empolyerStatusLabel.setImage(UIImage.init(named: "停用icon")?.withRenderingMode(.alwaysOriginal), for: .normal)
            default:
                cell.empolyerStatusLabel.setTitle("", for: .normal); cell.empolyerStatusLabel.setImage(UIImage.init(named: "edit")?.withRenderingMode(.alwaysOriginal), for: .normal)
            }
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let w = (kScreenWidth - 30) / 2
        let h: CGFloat = ScaleHeight(85)
        return CGSize(width: w, height: h)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(10, 10, 10, 10)
    }
    
    //    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    //        return CGSize(width: kScreenWidth - 20, height: 10)
    //    }
    
    
    
}
    


